package com.lebang.controller.api.donwn;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lebang.common.MemberLock;
import com.lebang.common.Require;
import com.lebang.component.RedisClient;
import com.lebang.domain.*;
import com.lebang.entity.RequestHeaders;
import com.lebang.entity.member.LbbMember;
import com.lebang.model.Whether;
import com.lebang.model.enums.Booleans;
import com.lebang.model.enums.buss.DownStatus;
import com.lebang.service.*;
import com.lebang.service.buss.MemberService;
import com.lebang.service.cences.CencesClickInfoService;
import com.lebang.service.sys.DictService;
import com.lebang.service.sys.DownFailConfigService;
import com.lebang.service.sys.PkgEarnInfoService;
import com.lebangweb.common.TextUtil;
import com.lebangweb.response.Callback;
import com.lebangweb.response.JsonData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Base64;
import java.util.Iterator;
import java.util.List;

import static com.lebang.service.DownAppService.CJS_EXPIRE_MEMBER;

/**
 * @Author: hwq
 * @Date: 2019/12/23 17:01
 * @Version 1.0
 */
@Api(tags = "下载任务")
@RestController
@RequestMapping("/app/download")
public class downApi {
    @Autowired
    private DownAppService downAppService;
    @Autowired
    private DictService dictService;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private TaskRouseDetailService taskRouseDetailService;
    @Autowired
    private AppHackerService appHackerService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private NewRouseService newRouseService;
    @Autowired
    private TaskRouseClickService taskRouseClickService;
    @Autowired
    private ClickStrategyDetailService clickStrategyDetailService;
    @Autowired
    private MemberNoticeService memberNoticeService;
    @Autowired
    private CpaService cpaService;
    @Autowired
    private CencesClickInfoService cencesClickInfoService;
    @Autowired
    private PkgEarnInfoService pkgEarnInfoService;
    @Autowired
    private DownFailConfigService downFailConfigService;







//    @Require
//    @PostMapping("/checkAppName")
//    @ApiOperation("查询库里有没有")
//    public JsonData checkAppName(HttpServletRequest request, @ApiParam(name = "应用名称") String appName) {
//        JSONObject jsonObject = new JSONObject();
//        if ("cc.gara.fish.jj_fish".equals(appName)) {
//            jsonObject.put("has_app", false);
//            jsonObject.put("money", 200);
//            return Callback.success("success", "查询成功", jsonObject);
//        }
//        DownloadPkgDetail status = downAppService.selectByAppName(appName);
//        if (status != null) {
//            jsonObject.put("has_app", true);
//            jsonObject.put("pkg_name", status.getPkgName());
//        } else {
//            jsonObject.put("has_app", false);
//        }
//        jsonObject.put("money", 200);
//        return Callback.success("success", "查询成功", jsonObject);
//    }



//    /**
//     * 第五步
//     *
//     * @param request
//     * @param recordId
//     * @param appName
//     * @param pkgName
//     * @return
//     */
//    @Require
//    @PostMapping("/upload")
//    @ApiOperation("上传包名")
//    public JsonData upload(HttpServletRequest request, @ApiParam(name = "任务id") Integer recordId,
//                           @ApiParam(name = "应用名称") String appName,
//                           @ApiParam(name = "包名") String pkgName) {
//        if(recordId==null){
//            return Callback.fail("200", "参数非法");
//        }
//        RequestHeaders requestHeaders = new RequestHeaders(request);
//        String memberId = requestHeaders.getUserid();
//        DownloadMemberRecord record = downAppService.selectByRecordId(recordId);
//        if (record == null) {
//            return Callback.fail("200", "任务不存在");
//        }
//        if (cpaService.getZyData().equals(record.getSdkKey())) {
//            return Callback.fail("200", "任务错误");
//        }
//        if (TextUtil.isEmpty(appName, pkgName) && record.getType().equals(1)) {
//            return Callback.fail("200", "任务不存在");
//        }
//        if (!record.getMemberId().equals(memberId)) {
//            return Callback.fail("200", "任务不存在");
//        }
//        if (!record.getStatus().equals(DownStatus.WAIT_PUSH.getIndex())) {
//            return Callback.fail("200", "任务不存在");
//        }
//        return Callback.success("success", "领取成功", downAppService.upload(record, appName, pkgName));
//    }





    @Require
    @PostMapping("/fail")
    @ApiOperation("放弃任务")
    public JsonData fail(HttpServletRequest request, Long recordId) {

        if(recordId==null){
            return Callback.fail("201", "参数非法");
        }
        RequestHeaders requestHeaders = new RequestHeaders(request);
        String memberId = requestHeaders.getUserid();
        DownloadMemberRecord record = downAppService.selectByRecordId(recordId);
        if (record == null) {
            return Callback.fail("200", "任务不存在");
        }
        int count =downAppService.getFailCount(requestHeaders);
        if (!record.getMemberId().equals(memberId)) {
            return Callback.fail("200", "任务不存在");
        }
        if (!record.getStatus().equals(DownStatus.WAIT_PUSH.getIndex())) {
            return Callback.fail("200", "任务不存在");
        }
        if (!TextUtil.isEmpty(record.getRouseDetailId())) {
            cpaService.fail(record);
        } else {
            downAppService.fail(record);
        }
        downAppService.addFailCount(requestHeaders);
        downFailConfigService.addFailCount(count,requestHeaders);
        DownFailConfig v=downFailConfigService.getFail(count,requestHeaders);

        return Callback.success("success", "查询成功","当前放弃次数:"+count+"累计放弃"+v.getFailCount()+"将被系统冻结"+v.getFailSecond()+"分钟");
    }

    @Require
    @PostMapping("/click/list")
    @ApiOperation("可签到列表")
    public JsonData clicklist(HttpServletRequest request) {
        RequestHeaders requestHeaders = new RequestHeaders(request);
        if (dictService.selectIntByKeyName("csj_click_enable") == 0) {
            return Callback.fail("200", "查询成功");
        }
        String memberId = requestHeaders.getUserid();
        List<MemberClickRouse> rouses;
        String cacheList = redisClient.hget(downAppService.getClickCacheKey(), memberId);
        if (cacheList == null) {
            rouses = downAppService.getClickList(memberId);
            if (rouses == null) {
                return Callback.fail("200", "查询成功");
            }
            redisClient.hset(downAppService.getClickCacheKey(), memberId, JSON.toJSONString(rouses));
        } else {
            rouses = JSON.parseArray(cacheList, MemberClickRouse.class);
        }
        List<TaskRouseClick> rouseClicks = taskRouseClickService.findAllList();
        //验证是否可以签到
        LocalDate now = LocalDate.now();
        for (Iterator<MemberClickRouse> iterator = rouses.iterator(); iterator.hasNext(); ) {
            MemberClickRouse s = iterator.next();
            //获取今天是签到起的第几天
            int days = (int) s.getCreateTime().toLocalDate().until(now, ChronoUnit.DAYS);
            if (!TextUtil.isEmpty(s.getRouseDetailId())) {
                TaskRouseDetail detail = taskRouseDetailService.selectById(s.getRouseDetailId().longValue());
                if (detail == null) {
                    iterator.remove();
                    continue;
                }
                if (detail.getIsClick().equals(Whether.NO.getDbIndex())) {
                    iterator.remove();
                    continue;
                }

                List<ClickStrategyDetail> clickStrategyDetails = taskRouseDetailService.selectByStrategyId(detail.getStrategyId());
                long lastDays = taskRouseClickService.getMaxDay(clickStrategyDetails);
                if (downAppService.checkClickByMemberId(memberId, s.getId(), s.getCreateTime().toLocalDate().plusDays(lastDays))) {
                    iterator.remove();
                    continue;
                }
                if (taskRouseClickService.checkLast(s, lastDays)) {
                    iterator.remove();
                    continue;
                }
                if (!cpaService.clickInitByDetail(s, days, now, clickStrategyDetails)) {
                    iterator.remove();
                }
            } else {
                long lastDays = taskRouseClickService.getMaxDay(rouseClicks, s.getRouseId());
                if (downAppService.checkClickByMemberId(memberId, s.getId(), s.getCreateTime().toLocalDate().plusDays(lastDays))) {
                    iterator.remove();
                    continue;
                }
                if (taskRouseClickService.checkLast(s, lastDays)) {
                    iterator.remove();
                    continue;
                }
                if (!downAppService.clickInit(s, days, rouseClicks, now)) {
                    iterator.remove();
                }
            }
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", rouses);
        jsonObject.put("type", 0);
        jsonObject.put("worth", 1000);
        return Callback.success("success", "查询成功", jsonObject);
    }


    @Require
    @PostMapping("/click")
    @ApiOperation("签到")
    @MemberLock
    public JsonData click(HttpServletRequest request, Integer clickId) {
        if(clickId==null){
            return Callback.fail("209", "非法参数");
        }
        RequestHeaders requestHeaders = new RequestHeaders(request);
        String memberId = requestHeaders.getUserid();
        RequestHeaders headers = new RequestHeaders(request);
        if (dictService.selectIntByKeyName("csj_click_enable") == 0) {
            return Callback.fail("200", "签到不存在.");
        }
        MemberClickRouse rouses = downAppService.findClickByClickId(clickId);
        if (rouses == null) {
            return Callback.fail("201", "签到不存在..");
        }
        TaskRouse taskRouse = newRouseService.selectById(rouses.getRouseId());
        if (taskRouse == null) {
            return Callback.fail("202", "签到不存在...");
        }
        if (taskRouse.getHasClick().equals(0)) {
            return Callback.fail("203", "签到不存在....");
        }
        if (!rouses.getMemberId().equals(memberId)) {
            return Callback.fail("204", "签到不存在.....");
        }
        if (!rouses.getStatus().equals(1)) {
            return Callback.fail("205", "签到不存在......");
        }

        LocalDateTime now = LocalDateTime.now();
        String nowStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        List<String> strings = JSON.parseArray(rouses.getClickJson(), String.class);
        if (downAppService.checkClickByMemberId(memberId, rouses.getId(), LocalDate.now())) {
            return Callback.fail("207", "今日已签到");
        }
        int star = taskRouseClickService.selectCountByClickId(rouses.getId()) + 1;
        int days = (int) rouses.getCreateTime().toLocalDate().until(now.toLocalDate(), ChronoUnit.DAYS);
        if (!TextUtil.isEmpty(rouses.getRouseDetailId())) {
            //自营的签到
            ClickStrategyDetail vo = clickStrategyDetailService.selectByDays(days, rouses);
            if (vo == null) {
                return Callback.fail("207", "当前应用不可签到");
            }
            //签到
            cpaService.clickAddByDetail(nowStr, rouses, strings, headers, vo, days, star);
            //查看下一次的提醒
            vo = clickStrategyDetailService.selectByDaysLess(days + 1, rouses);
            if (vo != null) {
                if (vo.getHasSendMsg().equals(Whether.YES.getDbIndex())) {
                    memberNoticeService.addNoticeAndPush("签到通知",
                            "恭喜完成《" + rouses.getAppName() + "》签到任务,该任务" + rouses.getCreateTime().plusDays(vo.getDayCount()).getDayOfMonth() + "号再签可得" + downAppService.getClickMoneyByRouseClickStr(vo) + "，请勿卸载",
                            memberId, headers);
                }
            } else {
                memberNoticeService.addNoticeAndPush("签到通知", "恭喜完成《" + rouses.getAppName() + "》全部签到任务", memberId, new RequestHeaders(request));
            }
        } else {
            //其他数据源签到
            TaskRouseClick vo = taskRouseClickService.selectByDays(days, rouses);
            if (vo == null) {
                return Callback.fail("207", "当前应用不可签到");
            }
            //签到
            downAppService.clickAdd(nowStr, rouses, strings, headers, vo, days, star);
            //查看下一天的提醒
            vo = taskRouseClickService.selectByDaysLess(days + 1, rouses);
            if (vo != null) {
                if (vo.getHasSendMsg().equals(Whether.YES.getDbIndex())) {
                    memberNoticeService.addNoticeAndPush("签到通知",
                            "恭喜完成《" + rouses.getAppName() + "》签到任务,该任务" + rouses.getCreateTime().plusDays(vo.getDayCount()).getDayOfMonth() + "号再签可得" + downAppService.getClickMoneyByRouseClickStr(vo) + "，请勿卸载",
                            memberId, headers);
                }
            } else {
                memberNoticeService.addNoticeAndPush("签到通知", "恭喜完成《" + rouses.getAppName() + "》全部签到任务", memberId, new RequestHeaders(request));
            }
        }
        redisClient.hdel(downAppService.getClickCacheKey(), memberId);
        cencesClickInfoService.addClick(headers, rouses, star, taskRouse);
        return Callback.success("success", "签到成功");
    }


    @Require
    @PostMapping("/sdk/add")
    @ApiOperation("上报数据源")
    public JsonData sdkadd(HttpServletRequest request, String sdkKey,
                           String pkgName, String appName,
                           String icon, String downUrl) {
        TaskRouse rouse = downAppService.selectByKey(sdkKey);
        if (rouse == null) {
            return Callback.fail("200", "上报失败");
        }
        taskRouseDetailService.add(pkgName, appName, downUrl, icon, rouse.getId());
        return Callback.success("success", "上报成功");
    }

    @Require
    @PostMapping("/sdk/get")
    @ApiOperation("取数据源")
    public JsonData getsdk(HttpServletRequest request, String sdkKey, Long recordId) {
        if(!TextUtil.isEmpty(recordId)){
            DownloadMemberRecord record = downAppService.selectByRecordId(recordId);
            record.setIsOp(1);
            downAppService.updateKey(record);
        }
        TaskRouseDetail detail = taskRouseDetailService.getSdk(sdkKey);
        if (detail == null) {
            return Callback.fail("200", "暂无数据");
        }
        detail.setOldUrl("");
        return Callback.success("success", "查询成功", detail);
    }

    @Require
    @PostMapping("/record/orderId")
    @ApiOperation("任务绑定订单id")
    public JsonData orderId(HttpServletRequest request, Long recordId, String orderId) {
        if(recordId==null){
            return Callback.fail("201", "参数非法");
        }
        RequestHeaders requestHeaders = new RequestHeaders(request);
        String memberId = requestHeaders.getUserid();
        DownloadMemberRecord record = downAppService.selectByRecordId(recordId);
        if (record == null) {
            return Callback.fail("200", "任务不存在");
        }
        if (!record.getMemberId().equals(memberId)) {
            return Callback.fail("200", "任务不存在");
        }
        if (!record.getStatus().equals(DownStatus.WAIT_PUSH.getIndex())) {
            return Callback.fail("200", "任务不存在");
        }
        record.setOrderId(orderId);
        downAppService.bindOrderIdByRecordId(record);
        return Callback.success("success", "绑定成功");
    }

    @PostMapping("/hacker")
    @ApiOperation("抓包数据上传")
    public JsonData hacker(HttpServletRequest request, Integer type) {
        RequestHeaders header = new RequestHeaders(request);
        AppHackerRecord record = new AppHackerRecord();
        record.setCreateTime(LocalDateTime.now());
        record.setMemberId(header.getUserid());
        record.setModifyTime(LocalDateTime.now());
        record.setHasDeleted(Whether.NO.getDbIndex());
        record.setAppStore(header.getAppStore());
        record.setVersion(header.getVersion());
        record.setImei(header.getImei());
        record.setIpAddress(header.getIpAddr());
        record.setMemberType(type);
        record.setUa(header.getUa());
        LbbMember member = memberService.getMemberByMemberId(header.getUserid());
        if (member != null) {
            record.setIphone(member.getPhone());
        }
        appHackerService.insertModel(record);
        return Callback.success("success", "上传成功");
    }

    @Require
    @PostMapping("/lock")
    @ApiOperation("锁定用户")
    public JsonData lock(HttpServletRequest request) {
        RequestHeaders requestHeaders = new RequestHeaders(request);
        String memberId = requestHeaders.getUserid();
        redisClient.setex(CJS_EXPIRE_MEMBER + memberId, 3600, memberId);
        return Callback.success("success", "查询成功");
    }

    @Autowired
    private CsjLogService csjLogService;
    final static Base64.Encoder encoder = Base64.getEncoder();
    final static Base64.Decoder decoder = Base64.getDecoder();

    //@Require
    @PostMapping("/add/log")
    @ApiOperation("添加日志")
    public JsonData addLog(HttpServletRequest request, String str) {
        String text = null;
        text = new String(decoder.decode(str.replaceAll(" +", "+").trim()), StandardCharsets.UTF_8);
        if (!TextUtil.isEmpty(text)) {
            CsjLog csjLog = new CsjLog();
            csjLog.setText(text);
            csjLog.setHasDeleted(Booleans.False.name());
            csjLog.setCreateTime(LocalDateTime.now());
            csjLogService.insertModel(csjLog);
        }
        return Callback.success("success", "成功");
    }

    @Require
    @PostMapping("/check/enable")
    @ApiOperation("检测开关")
    public JsonData checkenable(HttpServletRequest request, String key) {
        TaskRouse rouse = downAppService.selectByKey(key);
        return Callback.success("success", "查询成功", rouse.getEnable() > 0);
    }

    @Require
    @PostMapping("/open/return")
    @ApiOperation("检测开关")
    public JsonData openreturn(HttpServletRequest request, String key) {
        TaskRouse rouse = downAppService.selectByKey(key);
        return Callback.success("success", "查询成功", rouse.getEnable() > 0);
    }

    public static void main(String[] args) {
       // System.out.println("com.feka.games.merge.hamster.rat.mouse.form.power.collect.android".length());
    }
    @Require
    @PostMapping("/openCheck")
    @ApiOperation("检测开关")
    public JsonData openCheck(HttpServletRequest request,String pkgName,String appName,String icon){
        if(dictService.selectIntByKeyName("open_click_csj")==0){
            return Callback.success("success", "查询成功");
        }
        RequestHeaders requestHeaders = new RequestHeaders(request);
        DownloadMemberRecord record=new DownloadMemberRecord();
        record.setCreateTime(LocalDateTime.now());
        record.setModifyTime(LocalDateTime.now());
        record.setHasDeleted(0);
        record.setPkgName(pkgName);
        record.setAppName(appName);
        record.setType(0);
        record.setCategory(0);
        record.setMoney(0);
        record.setMemberId(requestHeaders.getUserid());
        record.setStatus(0);
        record.setTime(201);
        record.setEndTime(LocalDateTime.now());
        record.setRewardType(0);
        record.setUa(requestHeaders.getUa());
        record.setIpAddress(requestHeaders.getIpAddr());
        record.setImei(requestHeaders.getImei());
        record.setAppStore(requestHeaders.getAppStore());
        record.setOrderId("");
        record.setSdkKey("CSJ1");
        record.setRouseDetailId(0);
        record.setIsNewMember(0);
        record.setDownType(0);
        record.setIsOp(0);
        record.setReleaseTime(LocalDateTime.now());
        record.setPushTime(LocalDateTime.now());
        record.setSdkKeyAppStoreIsNew("");
        downAppService.clickInit(record,icon);
        //清除签到列表缓存
        redisClient.hdel(downAppService.getClickCacheKey(), requestHeaders.getUserid());
        return Callback.success("success", "查询成功");
    }
}
